package com.xc.disk.web.rest;

import com.xc.disk.info.TokenInfo;
import com.xc.disk.bean.UserInfoBean;
import com.xc.disk.config.Constants;
import com.xc.disk.dto.UserDto;
import com.xc.disk.entity.UserEntity;
import com.xc.disk.service.UserService;
import com.xc.tool.utils.Md5Utils;
import com.xc.tool.utils.ObjectUtils;
import com.xc.tool.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: 用户rest接口</p>
 * <P>创建人:小程 </p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/10/30</p>
 *
 * @version v1.0
 */
@RestController
public class UserRest {

    @Autowired
    private UserService userService;

    @Autowired
    private Constants constants;

    /**
     * 修改用户信息
     *
     * @param token        用户token
     * @param userInfoBean 用户信息参数
     */
    @PutMapping("/user")
    public UserDto updateUserInfo(TokenInfo token, @RequestBody UserInfoBean userInfoBean) {
        UserEntity userEntity = userService.getUserById(token.getUserId());
        if (userInfoBean.getIsUpdateSecret()) {
            String appId = StringUtils.generateAccount(constants.getPrefix());
            userEntity.setAppSecret(Md5Utils.getSaltMd5(appId));
        }
        userEntity.setAppName(userInfoBean.getAppName());
        return ObjectUtils.convert(new UserDto(), userService.updateUser(userEntity));
    }

    /**
     * 根据token获取用户信息
     *
     * @param token 用户token
     * @return 用户信息
     */
    @GetMapping("/user")
    public UserDto getUserByToken(TokenInfo token) {
        UserEntity userEntity = userService.getUserById(token.getUserId());
        return ObjectUtils.convert(new UserDto(), userEntity);
    }
}
